#!/usr/bin/python
import serial, sys, io

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

port0 = sys.argv[1]
file = sys.argv[2]

ser = serial.Serial()
ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1),
                             line_buffering = False)

#initialization and open the port
ser.port = port0
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = 5            #non-block read (1s time out)
ser.writeTimeout = 1     #timeout for write

try:
  ser.open()
except Exception, e:
  print("error opening serial port: %s", str(e))
  exit()

if ser.isOpen():
  try:
    ser.flushInput()  #flush input buffer, discarding all its contents
    ser.flushOutput() #flush output buffer, aborting current output and discard all that is in buffer
  except Exception, e1:
    print("error communicating...: %s", str(e1))
else:
  print("cannot open serial port")

f = open(file, 'w')

if(len(sys.argv) > 3):
    if(sys.argv[3] == '-v'):
        f = Tee(sys.stdout, f)

ser.write('1')
ser.flush()

i = 0
while(1):
    byte1 = ser.read().encode('hex')
    byte2 = ser.read().encode('hex')

    if(i%16 == 0):
            f.write('\n' + format(i, '08x'))
            f.write(' ')

    f.write(format(int(byte2, 16), '02x'))
    f.write(format(int(byte1, 16), '02x'))
    f.write(' ')
    f.flush()

    i = i + 2
